package com.lanou.moving.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.lanou.moving.R;
import com.lanou.moving.adapter.SearchEnterAadpter;
import com.lanou.moving.adapter.SearchListViewAdapter;
import com.lanou.moving.base.BaseActivity;
import com.lanou.moving.base.BaseApplication;
import com.lanou.moving.entity.SearchRoot;
import com.lanou.moving.entity.SearchSongEntity;
import com.lanou.moving.entity.SongSearch;
import com.lanou.moving.utils.MyConfig;
import com.lanou.moving.volley.FormatCodeUtil;
import com.lanou.moving.volley.GsonRequest;
import com.lanou.moving.volley.VolleySingleton;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by dllo on 15/10/22.
 */
public class SearchActivity extends BaseActivity implements View.OnClickListener {
    private Context mContext;
    private String url,urls;
    private List<SearchRoot.DataEntity> dataEntities;//实体类
    private SearchEnterAadpter enterAadpter;
    private ArrayList<SearchSongEntity> data;
    private SearchListViewAdapter adapter;//适配器
    private VolleySingleton volleySingleton;//单例
    private EditText search_edit;//搜索输入框
    private ImageView search_image, search_page_back;//返回
    private GridView gridView;
    private ListView songSearchLV;//列表布局
    private GsonRequest<SearchRoot> dataEntityGsonRequest;
    Handler myhandler = new Handler();//线程

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search_page);
        BaseApplication.getInstance().addActivity(this);
        mContext = this;
        search_edit = (EditText) findViewById(R.id.search_edit);
        search_image = (ImageView) findViewById(R.id.search_image);
        gridView = (GridView) findViewById(R.id.search_gridview);
        songSearchLV = (ListView) findViewById(R.id.songSearchLV);
        search_page_back = (ImageView) findViewById(R.id.search_page_back);
        search_page_back.setOnClickListener(this);// 返回
        search_image.setOnClickListener(this);
        songSearchLV = (ListView) findViewById(R.id.songSearchLV);
        volleySingleton = VolleySingleton.getInstance(this);
        songSearchLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                search_edit.setText(dataEntities.get(position).getVal());
            }
        });
        TextChanged();
        initData();
    }


    private void TextChanged() {
        search_edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                myhandler.post(eChanged);
            }
        });

    }

    Runnable eChanged = new Runnable() {
        @Override
        public void run() {
            //从searchETv组件获得数据
            String text = search_edit.getText().toString();
            String songUrl = FormatCodeUtil.codingFormat(text);

            //进行网址拼接
            urls = " http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.5.0&" +
                    "method=baidu.ting.search.catalogSug&format=json&query=" + songUrl;

            //进行网络请求
            StringRequest sr = new StringRequest(urls, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    //进行Gson数据解析
                    Gson gson = new Gson();
                    SongSearch songSearch = gson.fromJson(response, SongSearch.class);
                    //获得数据
                    data = songSearch.getSong();
                    //初始化适配器
                    adapter = new SearchListViewAdapter(mContext, data);
                    //绑定适配器
                    songSearchLV.setAdapter(adapter);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });
            volleySingleton.addQueue(sr);
            if (songUrl != null) {
                gridView.setVisibility(View.GONE);
                songSearchLV.setVisibility(View.VISIBLE);
            } else {
                gridView.setVisibility(View.VISIBLE);
                songSearchLV.setVisibility(View.GONE);
            }
        }
    };





    private void initData() {
        url = "http://api.dongting.com/misc/sug/billboard?"
                + "uid=866058021842951&f=f3040&v=v8.2.0.2015091720&app=ttpod&utdid=VSeGyjss0fEDAOqIktP5W%2BO4"
                + "&hid=1135212123029932&s=s200&alf=alf203200&imsi=460078098497828&tid=0&net=2&size=20";
        dataEntityGsonRequest = new GsonRequest<>(Request.Method.GET, url, SearchRoot.class, new
                Response.Listener<SearchRoot>() {
                    @Override
                    public void onResponse(SearchRoot response) {
                        dataEntities = response.getData();
                        enterAadpter = new SearchEnterAadpter(SearchActivity.this, dataEntities);
                        gridView.setAdapter(enterAadpter);

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        volleySingleton.addQueue(dataEntityGsonRequest);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search_page_back:
                finish();
                break;
            case R.id.search_image:
                String text = search_edit.getText().toString();
                if (text.length() <= 0) {
                    Toast.makeText(this, "请输入歌名...", Toast.LENGTH_LONG).show();
                } else {
                    try {
                        String string = URLEncoder.encode(text, "UTF-8");
                        MyConfig.putSharePre(SearchActivity.this, "Searchcontent", "url", string);
                        Intent intent = new Intent(SearchActivity.this, SearchContentActivity.class);
                        intent.putExtra("url", string);
                        startActivity(intent);

                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }
}
